//
//  DialogView.swift
//  
//
//  Created by tank on 2021/12/3.
//

import Foundation
import UIKit
import WebKit
import SnapKit
import SwiftMessages
import RxSwift
import RxCocoa

class DialogView: BaseView, Identifiable, AccessibleMessage {
    enum DialogType {
        case alert
        case confirm
    }

    static let alertButtons = """
<button id="confirm" class="button-col24" \
onclick="onButtonClick(this.id)">%@</button>
"""
    static let confirmButtons = """
<button id="cancel" class="button-col12" \
onclick="onButtonClick(this.id)">%@</button>
<button id="confirm" class="button-col12" \
onclick="onButtonClick(this.id)">%@</button>
"""

    static let dialogWidth = 270

    private let disposeBag = DisposeBag()

    public var accessibilityMessage: String?

    public var accessibilityElement: NSObject?

    public var additionalAccessibilityElements: [NSObject]?
    
    var id: String

    let contentView = UIView()

    let webView: WKWebViewEx
    
    private var webViewHeight: CGFloat = 100

    
    init(id: String, configuration: WKWebViewConfiguration? = nil) {
        self.id = id
        
        webView = WKWebViewEx(configuration: configuration,
                              frame: CGRect(x: 0, y: 0,
                                            width: DialogView.dialogWidth,
                                            height: 100))
        
        super.init(frame: .zero)
        
        backgroundColor = .clear
        
        contentView.backgroundColor = .clear
        addSubview(contentView)

        webView.isOpaque = false
        webView.backgroundColor = .clear
        webView.scrollView.backgroundColor = .clear
        contentView.addSubview(webView)
        
        webView.rx.didFinishLoad.subscribe { [weak self] _ in
            self?.webView.evaluateJavaScript("document.readyState", completionHandler: { (complete, error) in
                if complete != nil {
                    self?.webView.evaluateJavaScript("document.getElementsByTagName('body')[0].scrollHeight", completionHandler: { (height, error) in
                        guard let height = height as? CGFloat else {
                            return
                        }
                        self?.webViewHeight = height
                        self?.setNeedsUpdateConstraints()
                    })
                }

            })
        }.disposed(by: disposeBag)

        backgroundView = contentView
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func updateConstraints() {
        super.updateConstraints()

        webView.snp.updateConstraints { make in
            make.height.equalTo(webViewHeight)
            make.width.equalToSuperview()
            make.center.equalToSuperview()
        }

        contentView.snp.updateConstraints { make in
            make.center.equalToSuperview()
            make.height.equalTo(webView)
            make.width.equalTo(DialogView.dialogWidth)
        }
    }

    func set(dialogType: DialogType,
             title: String?, message: String,
             confirmButtonText: String? = nil, cancelButtonText: String? = nil) {
        guard let htmlPath = LibUI.shared.dataSource?.htmlPath,
              let resourceUrl = Bundle.main.url(forResource: htmlPath, withExtension: nil) else {
            return
        }

        guard var strHtml = Bundle.main.ex.string(forResource: "\(htmlPath)/dialog", withExtension: ".html") else {
            return
        }

        strHtml = strHtml.replacingOccurrences(of: "{{ dialogId }}", with: id)

        strHtml = strHtml.replacingOccurrences(of: "{{ title }}", with: title ?? "")

        strHtml = strHtml.replacingOccurrences(of: "{{ message }}", with: message)

        let confirmButtonText = confirmButtonText ?? "确定"
        let buttonsHtml: String
        if dialogType == .alert {
            buttonsHtml = String(format: DialogView.alertButtons, confirmButtonText)
        } else {
            let cancelButtonText = cancelButtonText ?? "取消"
            buttonsHtml = String(format: DialogView.confirmButtons, cancelButtonText, confirmButtonText)
        }

        strHtml = strHtml.replacingOccurrences(of: "{{ buttons }}", with: buttonsHtml)

        webView.loadHTMLString(strHtml, baseURL: resourceUrl)

        setNeedsUpdateConstraints()
    }
    
    func set(url: String?) {
        guard let url = url else {
            return
        }
        
        webView.load(url: url)
        setNeedsUpdateConstraints()
    }
}
